package org.madgecko.web;

import org.madgecko.basic.kit.BasicKit;
import org.madgecko.basic.model.SystemContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SystemContextFilter implements Filter{

    private final static Logger logger = LoggerFactory.getLogger(SystemContextFilter.class);

	private Integer pageSize;

	// filter的init方法在系统启动时执行，过来时不执行
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		try{
			pageSize = Integer.parseInt(filterConfig.getInitParameter("pageSize"));
		}catch(NumberFormatException nfe){
			pageSize = 5;
			System.out.println(pageSize);
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		Integer offset = 0;
		try{
			// 由于ExtJS使用的分页变量与JSP pager的分页变量的名称不同，所以需做判断
			String _startStr = request.getParameter("start");
			if(null==_startStr){
				_startStr = request.getParameter("pager.offset");
			}
			offset = Integer.parseInt(_startStr);
			String _limitStr = request.getParameter("limit");
			if(null!=_limitStr){
				pageSize = Integer.parseInt(_limitStr);
			}
		}catch(NumberFormatException nfe){
			offset = 0;
		}
		
		try{
		    // 初始化分页信息
			SystemContext.setPageOffset(offset);
			SystemContext.setPageSize(pageSize);
			SystemContext.setOrder(request.getParameter("order"));
			SystemContext.setSort(request.getParameter("sort"));
			if (BasicKit.isEmpty(SystemContext.getSystemPath())){
                SystemContext.setSystemPath(((HttpServletRequest)request).getSession().getServletContext().getRealPath("/"));
            }
            // 设置允许跨域
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Origin","*");
			chain.doFilter(request, response);
		}finally{
			SystemContext.removePageOffset();
			SystemContext.removePageSize();
			SystemContext.removeOrder();
			SystemContext.removeSort();
		}
	}

	@Override
	public void destroy() {
		
	}
	
}
